var app = new Vue({
    el:"#index",
    data () {
        return {
          items: [
            {
              image: "https://lay-image.oss-cn-shenzhen.aliyuncs.com/mall/banner/banner.jpg"
            },
            {
              image: "http://qnm.laykj.cn/image/banner1.jpg"
            },
            {
              image: "http://qnm.laykj.cn/image/banner2.jpg"
            },
            {
              image: "http://qnm.laykj.cn/image/spokesman.jpg"
            }
          ],
          newsData: [
            {
              title: "去哪买 | 时代的...",
              imgUrl: "/image/newsImage1.png",
              content: "当今，随着移动互联网的快速发展...",
              newsId: 2
            },
            {
              title: "去哪买 | 愿做你...",
              imgUrl: "/image/newsImage2.png",
              content: "可以想象，如果在大海中，没有罗盘...",
              newsId: 3
            },
            {
              title: "这个年代，服务...",
              imgUrl: "/image/newsImage3.png",
              content: "社会在发展，消费者对于服务的需...",
              newsId: 0
            },
            {
              title: "去哪买  人都是...",
              imgUrl: "/image/newsImage4.png",
              content: "16年之时马云讲过：“纯电商时代...",
              newsId: 1
            }
          ],
          searchKey: "", // 搜索框关键字
          tablist: [
            {
              title: "推荐商品"
            },
            {
              title: "价差排行"
            } /* ,
                {
                    title: '厨房直供'
                } */
          ],
          curIndex: 0,
          position: "bottom", // 加入购物车弹窗位置
          num: 1, // 加入购物车商品数量
          showPopup: false, // 其他超市弹窗是否展示
          popupTop: "", // 其他超市弹窗top
          popupIndex: 0, // 其他超市当前下标
          popupTriangle: "", // 其他超市弹窗三角位置
          triangleStyle: "", // 其他超市弹窗三角样式
          goodsData: null, // 商品数据
          scrollTop: 0, // 文档竖向滚动条偏移量
          addCartIndex: 0,
          marketData: null,
          cartBadge: null
        };
    },
    mounted () {
        window.addEventListener('scroll', () => {
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop || document.querySelector('.index-container').scrollTop            
            let header = document.querySelector('.index-header')
            if (scrollTop > 0) {
                header.style.background = 'url(../image/index-headerbg.jpg) repeat-x'
                header.style.backgroundSize = 'auto 100%'
            } else {
                header.style.background = 'none'
            }
        }, true)
    },
    created() {
        let url = window.location.href
        let accessToken = null
        if (url.indexOf('accessToken') !== -1) {
            let params = getUrlParams()
            accessToken = params.accessToken
            let domain = ''
            if (window.location.href.indexOf('laykj.cn')>-1) {
                domain = '.laykj.cn'
            } else {
                domain = document.domain
            }
            setCookie('accessToken', accessToken, 7,domain)
        }        
        this.getAddress()
        this.WeChatInit()
    },
    methods: {
        getAddress () {
            let accessToken = getCookie('accessToken')
            if (accessToken) {
              Axios.post('/user/address/getDefaultReceiveAddress.do', {}).then(res => {
                if (res.respCode === "F") {
                    this.$createDialog({
                        type: 'alert',
                        title: '温馨提示',
                        content: '您没有设置默认收货地址！',
                        confirmBtn: {
                            text: '去设置',
                            active: true,
                            disabled: false,
                            href: '../my/my_shouhuo.html'
                        }
                    }).show()
                } else {
                    Axios.post('goods/shopCar/listAdd.do', {}).then(res => {
                        if (res.respCode === 'S') {
                            let list = res.data.ShoppingCars
                            if (list.length < 100) {
                                localStorage.setItem('cartBadge', list.length)
                                this.cartBadge = list.length
                            } else {
                                localStorage.setItem('cartBadge', '99+')
                                this.cartBadge = '99+'
                            }
                            
                        }
                    })
                }
              }).catch(err => {
                console.error(err)
              })
            }
        },
        // tab切换
        /* changeTab (index) {
            this.curIndex = index
            if (index === 0) {
                this.getGoodsData()
            } else if (index === 1) {
                this.getSpreadData()
            }
        }, */
        // 获取推荐商品数据
        /* getGoodsData () {
            Axios.post('goods/goods/recommend.do', {
                currentPage: 1,
                pageSize: 4
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.data
                    list.forEach(item => {
                        item.minPrice = item.minPrice / 100
                        item.spreadRate = item.spreadRate
                    })
                    this.goodsData = list
                }
            })
        }, */
        // 获取价差排行数据
        /* getSpreadData () {
            Axios.post('goods/goods/differenceRanking.do', {
                currentPage: 1,
                pageSize: 4
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.data
                    list.forEach(item => {
                        item.minPrice = item.minPrice / 100
                        item.spreadRate = item.spreadRate
                    })
                    this.goodsData = list
                }
            })
        }, */
        // 直接下单
        /* placeOrder (index) {
            this.num = 1
            this.addCartIndex = index
            this.$refs.myPopup4.show()
        }, */
        // 加入购物车弹窗减号按钮
        /* reduce () {
            if (this.num > 1) {
                this.num--
            }
        }, */
        // 加入购物车加号按钮
        /* plus () {
            if (this.num < 99)  {
                this.num++
            }
        }, */
        /* addCart () {
            Axios.post('goods/shopCar/addShopCar.do', {
                goodsSkuId: this.goodsData[this.addCartIndex].goodsSkuId,
                quantity: this.num
            }).then(res => {
                if (res.respCode === 'S') {
                    const toast = this.$createToast({
                        txt: '您已提交成功<br/>请到购物车查看',
                        type: 'correct'
                    })                    
                    this.$refs.myPopup4.hide()
                    toast.show()
                }
            })
        }, */
        // 更多超市弹窗
        /* morePrice (e, index) {
            this.popupIndex = index
            let dom = e.currentTarget
            dom.style.opacity = 0
            let bodyHeight = document.body.clientHeight
            let top = dom.previousElementSibling.getBoundingClientRect().top
            let height = dom.previousElementSibling.getBoundingClientRect().height
            let popupTop
            let size = getComputedStyle(window.document.documentElement)['font-size']
            size = Number(size.substring(0, size.length - 2))
            let popupHeight = 4.3 * size
            if ((bodyHeight - top) > (popupHeight + 10)) {
                popupTop = top + height
                this.popupTriangle = 'top'
                let left = dom.getBoundingClientRect().left - (0.05 * size) - (0.72 * size)
                this.triangleStyle = 'top: -0.33rem; left:' + left
                this.popupTop = 'top:' + popupTop
            } else {
                popupTop = top - popupHeight
                this.popupTriangle = 'bottom'
                let left = dom.getBoundingClientRect().left - (0.05 * size) - (0.72 * size)
                this.triangleStyle = 'top:' + popupHeight + ';left:' + left
                this.popupTop = 'top:' + popupTop
            }
            Axios.post('goods/goods/supermarketPriceList.do', {
                goodsSkuId: this.goodsData[this.popupIndex].goodsSkuId
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.supermarketGoodsList
                    list.forEach(goods => {
                        if (goods.price == -1) {
                          goods.price = "暂无价格"
                        } else {
                          goods.price = goods.price / 100 + "元"
                        }          
                    })
                    this.marketData = list
                    this.showPopup = true
                }
            })
            let bodyEl = document.body
            this.scrollTop = window.scrollY
            bodyEl.style.position = 'fixed'
            bodyEl.style.top = -this.scrollTop
        }, */
        // 关闭更多超市弹窗
        /* closePopup () {
            let triangle = document.querySelectorAll('.index-triangle')
            triangle[this.popupIndex].style.opacity = 1
            this.showPopup = false
            let bodyEl = document.body
            bodyEl.style.position = ''
            bodyEl.style.top = ''        
            window.scrollTo(0, this.scrollTop)
        }, */
        // 搜索
        /* search (e) {
            if (e.keyCode === 13) {
                window.location.href = '/search/searchList.html?searchKey=' + this.searchKey
            }            
        }, */
        WeChatInit () {
            let url = location.href.split('#')[0]
            Axios.post('user/weixin/getSignature.do', {
                htmlUrl: url
            }).then(res => {
                if (res.respCode === 'S') {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: res.data.appid, // 必填，公众号的唯一标识
                        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: res.data.noncestr, // 必填，生成签名的随机串
                        signature: res.data.signature,// 必填，签名
                        jsApiList: ['scanQRCode'] // 必填，需要使用的JS接口列表
                    })                    
                }
            })
        },
        WeChatScan () {            
            let self = this
            if (!self.isWeChat()) {
                this.toast = this.$createToast({
                    txt: '扫一扫只能在微信中使用',
                    type: 'txt'
                })
                this.toast.show()
            }
            wx.ready(() => {
                wx.scanQRCode({
                    needResult: 1,
                    scanType: ["barCode"],
                    success: res => {
                        let key = res.resultStr
                        key = key.split(',')
                        key = key[1]
                        window.location.href = '/search/searchList.html?barcode=' + key
                    }
                })
            })
            wx.error(res => {
                console.log(res.errMsg)
            })
        },
        isWeChat () {
            let ua = navigator.userAgent.toLowerCase()
            if(ua.match(/MicroMessenger/i)=="micromessenger") {
                return true
            } else {
                return false
            }
        }
     }
})